package com.gopay.checkorder.service.alarm;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.common.domain.bank.CheckOrderFailLog;

/**
 * 订单报警记录存储者
 * 
 * @OrderAlarmRecordStorage.java
 * @author fanghw
 * @2016年1月8日 下午4:35:16  www.gopay.com.cn Inc.All rights reserved.
 */
@Service("orderAlarmRecordStorage")
public class OrderAlarmRecordStorage {

    private final static Logger logger = LoggerFactory.getLogger(OrderAlarmRecordStorage.class);
   
    @Resource(name = "smsConfig")
    private Map<String, String> smsConfig;

    @Resource(name = "bankList")
    private List<String> bankList;
    
    @Resource(name = "bankOrderManager")
    protected BankOrderManager bankOrderManager;
    
    
    public void store(OrderAlarmDataCollector collector) {
        
        for (String bankCode : bankList) {
            if(StringUtils.isBlank(bankCode)){
                continue;
            }
            
            int total=collector.getTotal(bankCode);
            int fail=collector.getFail(bankCode);
            double failScale=collector.calFailScale(bankCode);
            
            logger.error("total count:"+total);
            logger.error("total fail:"+fail);
            //系统配置失败比例
            Integer scale = Integer.valueOf(smsConfig.get("scale"));
            if (failScale >= scale.doubleValue()) {
                // 对账报警对象
                CheckOrderFailLog checkOrderFailLog = new CheckOrderFailLog();
                checkOrderFailLog.setBankCode(bankCode);
                checkOrderFailLog.setTransTime(new Date());
                checkOrderFailLog.setCheckCount(total);
                checkOrderFailLog.setFailCount(fail);
                checkOrderFailLog.setFailureRate(failScale);
                checkOrderFailLog.setRemark(bankCode + "通讯异常");

                bankOrderManager.insertCheckOrderFailLog(checkOrderFailLog);
                
                logger.error(bankCode + "对账失败率超过阈值报警");
            }
        }

    }
}
